package com.owulia.coffee.mongo;

import com.mongodb.client.result.UpdateResult;
import com.owulia.coffee.CoffeeApplicationTests;
import com.owulia.coffee.entity.mongo.CoffeeMongo;
import lombok.extern.slf4j.Slf4j;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Update;

import java.util.Date;
import java.util.List;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

@Slf4j
public class MongoDome extends CoffeeApplicationTests{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    public void domeTests() throws InterruptedException {
        CoffeeMongo espresso = CoffeeMongo.builder()
                .name("espresso")
                .price(Money.of(CurrencyUnit.of("CNY"), 20.0))
                .createTime(new Date())
                .updateTime(new Date()).build();
        CoffeeMongo saved = mongoTemplate.save(espresso);
        log.info("Coffee {}", saved);

        List<CoffeeMongo> list = mongoTemplate.find(
                query(where("name").is("espresso")), CoffeeMongo.class);
        log.info("Find {} Coffee", list.size());
        list.forEach(c -> log.info("Coffee {}", c));
        Thread.currentThread().sleep(1000); // 为了看更新时间
        UpdateResult result = mongoTemplate.updateFirst(query(where("name").is("espresso")),
                new Update().set("price", Money.ofMajor(CurrencyUnit.of("CNY"), 30))
                        .currentDate("updateTime"),
                CoffeeMongo.class);
        log.info("Update Result: {}", result.getModifiedCount());
        CoffeeMongo updateOne = mongoTemplate.findById(saved.getId(), CoffeeMongo.class);
        log.info("Update Result: {}", updateOne);

        mongoTemplate.remove(updateOne);
    }
}
